<template>
  <div class="app-container">
    <section>

      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true">
          <el-form-item>
            <el-date-picker
              :picker-options="pickerOptions"
              v-model="form.date"
              @change="dateChangebirthday1"
              type="daterange"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        
          <el-form-item label="供应商" prop="OrderStatus">
            <el-select v-model="form.SupplierId" filterable clearable placeholder="请选择供应商">
              <el-option
                v-for="item in SupplierList"
                :key="item.SupplierId"
                :label="item.SupplierName"
                :value="item.SupplierId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
           <!-- 商品系数 -->
            <span style="font-size:14px;font-weight:700;color:#333;margin-left:12px;">采购系数</span>
            <el-input v-model="Cfgoods" style="width:60px;margin-left:12px;margin-right:12px;" size="medium" @blur="Burltext($event)"></el-input>
            <el-button type="primary" @click="GeReplenishmentProposal()">查询</el-button>
            <!-- 生成采购订单 -->
            <el-button type="primary" @click="handleShop()">生成采购订单</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <!-- 表格 -->
      <el-table
        :data="List2"
        border
        height="750"
        ref="multipleTable"
        v-loading.fullscreen.lock="loading"
        @selection-change="handleSelectionChange"
        :header-cell-style="{'background':'#F5F7FA','color':'#000',}"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="OldSKUSupplierId" label="货号" align="center"></el-table-column>
        <el-table-column prop="SKUUnitNo" label="单位" align="center"></el-table-column>
        <el-table-column prop="SKUInPrice" label="价格" align="center"></el-table-column>
        <el-table-column prop="SKUName" label="商品名" align="center"></el-table-column>
        <el-table-column prop="SupplierName" label="供货商" align="center">
          <template  slot-scope="scope">
            <el-select v-model="scope.row.SupplierId" filterable placeholder="请选择供应商">
              <el-option
                v-for="item in SupplierList"
                :key="item.SupplierId"
                :label="item.SupplierName"
                :value="item.SupplierId"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="saleqty" label="销售数量" align="center"></el-table-column>
        <el-table-column prop="stockqty" label="当前库存" align="center"></el-table-column>
        <el-table-column prop="ActualQty" label="建议采购数" align="center">
          <template slot-scope="scope">
            <span> {{ scope.row.ActualQty }} </span>
            <!-- <el-input v-model="scope.row.Qty"  @blur="Burltext($event)" style="width:100px" ></el-input> -->
          </template>
        </el-table-column>
        <el-table-column prop="Qty" label="实际采购数" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.Qty"  @blur="Burltext($event)" style="width:100px" ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          background
          layout=" prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          :page-size="PageSize"
          :total="total"
          style="float:right;margin-top: 10px;"
        ></el-pagination>
      </div>
    </section>
  </div>
</template>

<script>
import { GeReplenishmentProposal, PurchaseGetSupplierList, GetPurchaseOrdersAdd, AddPurchaseOrders } from "@/api/api";
import Config from "../../api/config";
export default {
  data() {
    return {
      // 建议采购数
      Qty: 7,
      //商品系数
      Cfgoods:'1',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },

        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本周",
            onClick(picker) {
              const end = new Date();
              console.log(this);
              console.log(formatDate);
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              var weekStartDate = new Date(
                nowYear,
                nowMonth,
                nowDay - nowDayOfWeek
              );
              const start = weekStartDate;
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "上周",
            onClick(picker) {
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              const start = new Date(
                nowYear,
                nowMonth,
                nowDay - nowDayOfWeek - 7
              );
              start.setTime(start);
              const end = new Date(
                nowYear,
                nowMonth,
                nowDay - nowDayOfWeek - 1
              );
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本月",
            onClick(picker) {
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              const end = new Date();
              const start = new Date(nowYear, nowMonth, 1);
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "上月",
            onClick(picker) {
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              var lastMonthDate = new Date(); //上月日期
              lastMonthDate.setDate(1);
              lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
              var lastYear = lastMonthDate.getYear();
              var lastMonth = lastMonthDate.getMonth();
              //								const end = new Date();
              const start = new Date(nowYear, nowMonth - 1, 1);
              start.setTime(start);
              const end = new Date(
                nowYear,
                nowMonth - 1,
                getMonthDays(lastMonth)
              );
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "近3天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "近5天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 5);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "近7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近10天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 10);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      SupplierList: [],
      List: [],
      Page: 1,
      PageSize: 100,
      total: 0,
      List2: [],
      form: {
        date: []
      },
      BranchId: 15,
      loading: false
    };
  },
  created() {
    this.PurchaseGetSupplierList();
    this.getTime();
  },
  methods: {
    //input 输入框的验证
    Burltext(e){
      let booler=new RegExp("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$").test(e.target.value);
      if(!booler){this.$message.warning("请输入数字");e.target.value='';}
    },
    //获取供应商列表
    PurchaseGetSupplierList() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: this.page,
        PageSize: 20000
      };
      PurchaseGetSupplierList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取供应商列表", vdata);
          var list = vdata.DataList;
          self.SupplierList = list;
        }
      });
    },
    getTime() {
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let dt = date.getDate() - 1;
      let endTime = y + "-" + m + "-" + d;
      let starttime = y + "-" + m + "-" + dt;
      this.form.date[0] = starttime;
      this.form.date[1] = endTime;
      this.GeReplenishmentProposal();
    },
    dateChangebirthday1(val) {
      this.startTime = val;
      console.log(this.startTime);
    },
    GeReplenishmentProposal() {
      var parm = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: this.Page,
        PageSize: this.PageSize,
        StartDate: this.form.date[0],
        EndDate: this.form.date[1],
        SupplierId: this.form.SupplierId
      };
      GeReplenishmentProposal(parm).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          //获取订单列表
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取采购订单表体列表");
          console.log(vdata);
          console.log("测试建议采购数")
          for(var i of vdata.DataList){
            i.Qty=this.Cfgoods*i.saleqty-i.stockqty < 0 ? 0 : this.Cfgoods*i.saleqty-i.stockqty;
            i.ActualQty=this.Cfgoods*i.saleqty-i.stockqty < 0 ? 0 : this.Cfgoods*i.saleqty-i.stockqty;
          }
          console.log(vdata)

          this.List2 = vdata.DataList;
          console.log(this.List2,"表格")
          this.total = vdata.TotalCount;
        }
      });
    },

    handleShop() {
      if (this.List.length == 0) {
        this.$message({
          message: "您还没有勾选任何商品",
          type: "error"
        });
        return;
      } else {
        var a = this.List;
        console.log(a);
        localStorage.setItem("huo", JSON.stringify(a));
        // this.$router.push({
        //   path: "/Purchase/Orders",
        //   query: {
        //     huo: 123
        //   }
        // });
        var data1 = JSON.parse(localStorage.getItem("huo"));
        console.log("输出缓存数组", data1);
        // 1.创建映射
        let map = this.List.reduce((p, c) => [p[c.SupplierId] = p[c.SupplierId] || [],
                                       p[c.SupplierId].push({
                                         ProductId: c.ProductId,
                                         Unit: c.SKUUnitNo,
                                         Qty: c.Qty,
                                         Price: c.SKUInPrice,
                                         DiscountRate: 1,
                                         IsGift: 0
                                       }), p][2], {})

        // 2.获取映射分类下的数组 
        let _result = []                 
        Object.keys(map).map(i => {
          let newMap = map[i].filter(item => item.Qty !== 0)
          if (newMap.length !== 0) {
            let params = {}
            params.SupplierId = i;
            params.tempList = newMap;
            _result.push(params);
          }
        });
        console.log(_result, '已过滤数组')
        // 直接生成采购订单
        if (_result.length !== 0) {
          this.loading = true;
          this.onGetPurchaseOrdersAdd(_result)
        } else {
          this.$message({
            message: '实际采购数不能为0',
            type: "error"
          });
        }
      }
    },

    /**
     * @Author: 王灿
     * @Descripttion: 直接生成订单 获取采购订单编号等信息
     * @Date: 2019-12-14 08:58:40
     */
    onGetPurchaseOrdersAdd(_resultParams) {
      GetPurchaseOrdersAdd({
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Exter: "CG"
      }).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取采购表头", vdata);
          let params = {
            SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
            Creater: vdata.Creater,
            SupplierId: _resultParams[0].SupplierId,
            BranchId: this.BranchId,
            Summary: '',
            tempList: _resultParams[0].tempList
          }
          this.onAddPurchaseOrders(params, _resultParams);
        }
      }).catch(() => {
        this.loading = false
      });
    },
    /**
     * @Author: 王灿
     * @Descripttion: 新增采购订单
     * @Date: 2019-12-14 09:05:49
     */
    onAddPurchaseOrders(params, _resultParams) {
      AddPurchaseOrders(params).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
        } else {
          // 删除已创建订单数据
          _resultParams.shift(0)
          if (_resultParams.length) {
            // 若有 -- 继续新增采购订单
            this.onGetPurchaseOrdersAdd(_resultParams)
          } else {
            // 若无 -- 关闭 loading
            this.$message({
              message: res.data.Description,
              type: "success",
              duration: 1000,
              onClose: () => {
                this.loading = false;
              }
            });
          }
        }
      }).catch(() => {
        this.loading = false
      });
    },

    //选择器
    handleSelectionChange(val) {
      console.log(val);
      this.List = val;
    },
    //翻页
    handleCurrentChange(val) {
      this.Page = val;
      this.GeReplenishmentProposal();
    }
  }
};
</script>